package com.xueyi.starter.redis;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.Resource;

/**
 * 描述 Redis自动装配
 *
 * @author 俞烨
 * @date 2024-03-09 14
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(RedisConfigProperties.class)
public class RedisAutoConfiguration {


    @Resource
    private RedisConfigProperties redisConfigProperties;

    @Bean
    public JedisPool jedisPool() {

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisConfigProperties.getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisConfigProperties.getMaxWaitMillis());
        jedisPoolConfig.setMaxTotal(redisConfigProperties.getMaxActive());
        jedisPoolConfig.setMinIdle(redisConfigProperties.getMinIdle());


        return new JedisPool(jedisPoolConfig,
                redisConfigProperties.getHost(),
                redisConfigProperties.getPort(),
                redisConfigProperties.getTimeout(),
                redisConfigProperties.getPassword());
    }


    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + redisConfigProperties.getHost() + ":" + redisConfigProperties.getPort()).setPassword(redisConfigProperties.getPassword());
        return Redisson.create(config);
    }
}
